package com.strato.sequence.jdbc.v1_0_0;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;

import com.strato.annotation.osgi.v1_0_0.service.OsgiService;
import com.strato.jdbc.datasource.v1_0_0.DataSourceFactory;
import com.strato.orm.mybatis.v1_0_0.annotation.MybatisWired;
import com.strato.sequence.base.v1_0_0.SequenceService;
import com.strato.sequence.jdbc.v1_0_0.dao.mapper.CommonSequenceExtendMapper;
import com.strato.sequence.jdbc.v1_0_0.dao.mapper.MerchantSequenceExtendMapper;

@OsgiService
public class JdbcSequenceService implements SequenceService {

	@MybatisWired(datasource=DataSourceFactory.MERCHANT_DATASOURCE)	
	MerchantSequenceExtendMapper merchantSequenceExtendMapper;
	
	
	@MybatisWired(datasource=DataSourceFactory.COMMON_DATASOURCE)	
	CommonSequenceExtendMapper commonSequenceExtendMapper;
	
	private static final String DEFAULT_PATTERN = "###################0";
	
	@Override
	public String nextval(String name,String merchantId,String pattern) {
		if(pattern==null||pattern.trim().equals("")){
			pattern=DEFAULT_PATTERN;
		}
		
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("sequenceName", name);
		paramMap.put("merchantId", merchantId);
		merchantSequenceExtendMapper.getNextVal(paramMap);
		long val = (long)paramMap.get("currentValue");
		
		NumberFormat nf=new DecimalFormat(pattern);
		return nf.format(val); 
	}

	@Override
	public String nextval(String name, String pattern) {
		if(pattern==null||pattern.trim().equals("")){
			pattern=DEFAULT_PATTERN;
		}
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("sequenceName", name);
		commonSequenceExtendMapper.getNextVal(paramMap);
		long val = (long)paramMap.get("currentValue");
		
		NumberFormat nf=new DecimalFormat(pattern);
		return nf.format(val);
	}
}
